define([
	'../libs/jquery',
	'../common/dialog',
	'../common/ajax',
	'../common/yingSoftPrg',
	'../common/yingSoftCookie',
	'../common/storage',
	'../common/yingSoftSetTest',
	'../common/agentInfo',
	'../common/userAction',
	'../common/maiDianApi'
], function() {
	initUserLogin();
	function initUserLogin() {
		G_UserAction.loadObject();
		G_AgentInfo.loadIcon();
//		UserLogin();
		
	}


		function _setClickEven() {
			var isFreeTry = false;
			G_Prg.$('free').onclick = function() {
				console.log(123)
				if(typeof(G_maiDian) !== 'undefined') {
					G_maiDian.probationClickCount(); //埋点用户试用
				}
				G_UserAction.addUserAction('freeTrialBtn');
				G_Prg.$('free').onclick = function() {};
				
				freeTry();
			};
		}


		function _login(isFreeTry) {
			var userName = G_Prg.$('txtName').value;
			if(!_checkUserName()) {
				return;
			}
			var loginType = 1;
			if(G_Prg.checkEmail(userName)) {
				loginType = 2;
			}
			if(G_Prg.checkCellPhone(userName)) {
				loginType = 3;
			}
			var userPassword = G_Prg.$('pswPassword').value;
			var cookiePwd = G_Cookie.getUserPwd();
			var userPasswordMd5 = '';
			var pwdArr = null;
			if(cookiePwd) {
				pwdArr = cookiePwd.split(',');
			}
			if(cookiePwd && pwdArr && userPassword === pwdArr[0].substring(0, Number(pwdArr[1]))) {
				userPasswordMd5 = pwdArr[0];
			} else {
				if(!_checkPwd()) {
					return;
				}
				userPasswordMd5 = hex_md5(userPassword);
			}
			var _success = function(json) {
				if(!json) {
					window.scrollTo(0, 0);
					G_Prg.throw('程序运行错误，UserLogin._login服务端无返回数据');
				}
				var jsonData = JSON.parse(json);
				if(jsonData.status === 200) {
					//保存一些必要的Cookie
					var clientType = G_Cookie.getClientType();
					var iosVersion = G_Prg.getCookie('IOSVERSION');
					var androidVersion = G_Prg.getCookie('VERSION');
					var phoneID = G_Prg.getCookie('PHONEID');
					G_Prg.cleanCookie();
					G_Prg.setCookie('PHONEID', phoneID);
					G_Cookie.setClientType(clientType);
					G_Prg.setCookie('IOSVERSION', iosVersion);
					G_Prg.setCookie('VERSION', androidVersion);
					G_Cookie.setUserID(jsonData.data.userID);
					G_Cookie.setUserName(userName);
					G_Cookie.setGuid(jsonData.data.guid);
					G_Prg.setCookie('NICKNAME', jsonData.data.NickName);
					if(_isRemPwd) {
						G_Cookie.setUserPwd(userPasswordMd5 + ',' + userPassword.length);
					} else {
						G_Cookie.removeUserPwd();
					}
					_loginSuccess(isFreeTry, jsonData);
				} else if(jsonData.status === 201) {
					window.scrollTo(0, 0);
					G_Prg.alert('用户名或者密码不正确');
					G_Prg.$('pswPassword').value = '';
				} else if(jsonData.status === 300) {
					window.scrollTo(0, 0);
					if(typeof(G_maiDian) !== 'undefined') {
						G_maiDian.setBugRecordInfos('程序错误', '登录', jsonData.status + ':' + jsonData.msg);
					}
					G_Prg.throw('程序运行错误，UserLogin._login,数据库获取数据异常');
				} else if(jsonData.status >= 400 && jsonData.status < 500) {
					if(typeof(G_maiDian) !== 'undefined') {
						G_maiDian.setBugRecordInfos('业务逻辑错误', '登录', jsonData.status + ':' + jsonData.msg);
					}
				} else {
					window.scrollTo(0, 0);
					if(typeof(G_maiDian) !== 'undefined') {
						G_maiDian.setBugRecordInfos('其它程序错误', '登录', jsonData.status + ':' + jsonData.msg);
					}
					G_Prg.throw('抱歉，UserLogin._login不能处理 status = "' + jsonData.status + '"！');
				}
			}
			var agentCode = G_AgentInfo.getAgentCode();
			var URL = '/api/user/login/' + userName + '/' + userPasswordMd5 + '/' + loginType + '/' + _getClientType() + '/' + _getUserAgent();
			G_AjaxApi_Record.get(URL, false, _success);
		}

		function _loginSuccess(isFreeTry, jsonData) {
			if(G_Cookie.getLoginURL()) {
				if(!G_Cookie.getAppID() && !G_Cookie.getAppName() && !G_Cookie.getAppEName() && jsonData.data.appID && jsonData.data.appEName && jsonData.data.appName) {
					G_Cookie.setSelectedApp(jsonData.data.appName, jsonData.data.appEName, jsonData.data.appID);
				}
				window.location.href = G_Cookie.getLoginURL();
				G_Cookie.removeLoginURL();
				return;
			}
			if(!G_Cookie.getAppID() && !G_Cookie.getAppName() && !G_Cookie.getAppEName() && jsonData.data.appID && jsonData.data.appEName && jsonData.data.appName) {
				G_Cookie.setSelectedApp(jsonData.data.appName, jsonData.data.appEName, jsonData.data.appID);
				if(G_Storage.checkSessionStorageSupport) {
					G_Storage.removeSessionStorageValue('firstLoad');
				}
				if(G_Storage.checkSessionStorageSupport) {
					G_Storage.removeSessionStorageValue('showTime');
				}
				window.location.href = 'default.html';
				return;
			}
			if(!G_Cookie.getAppName() && jsonData.data.isVip === false) {
				window.location.href = 'softMenu.html';
				return;
			}
			var fromUrl = G_Prg.getQueryString('fromUrl');
			var toUrl = G_Prg.getQueryString('toUrl');
			if(fromUrl === 'doExam.html') {
				if(toUrl && !G_Prg.checkVipApp()) {
					G_GoBuySoft.goBuySoft('', 'selectPrice.html?fromUrl=doExam.html&cptName=' + G_Prg.getQueryString('cptName', true));
					return;
				}
				window.location.href = 'doExam.html?fromUrl=chapterMenu.html&cptName=' + G_Prg.getQueryString('cptName', true);
				return;
			}
			if(fromUrl === 'chapterMenu.html') {
				window.location.href = 'chapterMenu.html?fromUrl=userLogin.html';
				return;
			}
			if(fromUrl === 'testInfoMenu.html') {
				window.location.href = 'testInfoMenu.html?fromUrl=userLogin.html&lastMenuID=' + G_Prg.getQueryString('lastMenuID', true);
				return;
			}
			if(!toUrl || toUrl === 'default.html') {
				if(G_Storage.checkSessionStorageSupport) {
					G_Storage.removeSessionStorageValue('firstLoad');
				}
				if(G_Storage.checkSessionStorageSupport) {
					G_Storage.removeSessionStorageValue('showTime');
				}
				window.location.href = 'default.html';
				return;
			}
			window.location.href = toUrl + '?fromUrl=default.html';
		}

		function _checkUserName() {
			var userName = G_Prg.$('txtName').value;
			if(!userName) {
				G_Prg.$('TelephonePrompt').innerHTML = '*请输入通行证';
				return false;
			}
			if(userName.length > 100) {
				G_Prg.$('TelephonePrompt').innerHTML = '*通行证的长度必须小于100个字符';
				return false;
			}
			G_Prg.$('TelephonePrompt').innerHTML = '';
			return true;
		}

		function _checkPwd() {
			var userPassword = G_Prg.$('pswPassword').value;
			if(!userPassword) {
				G_Prg.$('PasswordPrompt').innerHTML = '*请输入密码';
				return false;
			}
			if(userPassword.length < 6 || userPassword.length > 20) {
				G_Prg.$('PasswordPrompt').innerHTML = '*密码长度必须为6-20个字符';
				return false;
			}
			G_Prg.$('PasswordPrompt').innerHTML = '';
			return true;
		}

		function _backClick() {
			var fromUrl = G_Prg.getQueryString('fromUrl');
			if(fromUrl === 'doExam.html') {
				window.location.href = fromUrl + '?&cptName=' + G_Prg.getQueryString('cptName', true);
				return;
			}
			if(fromUrl === 'testInfoMenu.html') {
				window.location.href = 'testInfoMenu.html?fromUrl=userLogin.html&lastMenuID=' + G_Prg.getQueryString('lastMenuID', true);
				return;
			}
			if(fromUrl) {
				window.location.href = fromUrl + '?fromUrl=userLogin.html';
			} else {
				window.location.href = 'default.html';
			}
		}

		function autoRemPwd() {
			G_UserAction.addUserAction('remPsdCb');
			_setRemPwd();
		}


	function freeTry() {
		var clientType = G_Prg.getQueryString('clientType', true);
		var clientTypeCookie = G_Cookie.getClientType();
		if(clientType === 'iphone' || clientTypeCookie === 'iphone') {
			var data = {
				"agentCode": G_AgentInfo.getAgentCode(),
				"guid": G_Cookie.getGuid(),
				"clientType": clientType
			}
			G_AjaxApi_Record.post('/api/user/freeFegist/', data, false, function(json) {
				var jsonData = JSON.parse(json);
				if(jsonData && jsonData.status === 200) {
					//保存一些必要的Cookie
					var clientType = G_Cookie.getClientType();
					var iosVersion = G_Prg.getCookie('IOSVERSION');
					var androidVersion = G_Prg.getCookie('VERSION');
					G_Prg.cleanCookie();
					G_Cookie.setClientType(clientType);
					G_Prg.setCookie('IOSVERSION', iosVersion);
					G_Prg.setCookie('VERSION', androidVersion);
					G_Cookie.setUserID(jsonData.data.userID);
					G_Cookie.setUserName(jsonData.data.userName);
					G_Cookie.setGuid(jsonData.data.guid);
					G_Prg.setCookie('NICKNAME', jsonData.data.NickName);
					document.location.href = 'softMenu.html';
					return;
				}
				if(jsonData && (jsonData.status === 201 || jsonData.status === 203)) {
					G_Prg.alert(jsonData.msg);
					return;
				}
				if(jsonData.status === 300) {
					window.scrollTo(0, 0);
					if(typeof(G_maiDian) !== 'undefined') {
						G_maiDian.setBugRecordInfos('程序错误', '登录', jsonData.status + ':' + jsonData.msg);
					}
					G_Prg.throw('程序运行错误，UserLogin._login,数据库获取数据异常');
				} else if(jsonData.status >= 400 && jsonData.status < 500) {
					if(typeof(G_maiDian) !== 'undefined') {
						G_maiDian.setBugRecordInfos('业务逻辑错误', '登录', jsonData.status + ':' + jsonData.msg);
					}
				} else {
					window.scrollTo(0, 0);
					if(typeof(G_maiDian) !== 'undefined') {
						G_maiDian.setBugRecordInfos('其它程序错误', '登录', jsonData.status + ':' + jsonData.msg);
					}
					G_Prg.throw('程序运行错误!:"' + jsonData.msg + '"!status:' + jsonData.status);
				}
			});
		} else {
			document.location.href = 'softMenu.html?fromUrl=userLogin.html';
		}
	}

	function _getClientType() {
		var browser = {
			versions: function() {
					var u = navigator.userAgent,
						app = navigator.appVersion;
					return {
						ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
						android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1,
						iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1,
						iPad: u.indexOf('iPad') > -1,
						webApp: u.indexOf('Safari') == -1
					};
				}
				()
		};
		if(browser.versions.iPhone || browser.versions.iPad) {
			return 'web_iPhone';
		}
		if(browser.versions.ios || browser.versions.android || browser.versions.webApp) {
			return 'web_android';
		}
		return 'web_pc';
	}
	//自动勾选记住密码
	function _getUserAgent() {
		var userAgent = navigator.userAgent.split('/');
		return userAgent;
	}

})